{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8ce67390",
   "metadata": {},
   "source": [
    "# 前言\n",
    "通过本文，你可以：\n",
    " * 了解AppBuilder KnowledgeBase MCP Server是什么\n",
    " * 了解如何通过AppBuilder-SDK调用AppBuilder KnowledgeBase MCP Server\n",
    " * 了解如何通过Cursor调用AppBuilder KnowledgeBase MCP Server\n",
    "\n",
    "如果你需要了解更多关于AppBuilder结合MCP生态的功能,可跳转到下面的文档：\n",
    "- 主动调用：通过AppBuilder-Agent调用MCP Server\n",
    "  - 代码态调用：[AppBuilder结合端云组件，调用本地MCP Server](./client.ipynb) \n",
    "  - 代码态调用：[AppBuilder结合地图MCP Server，实现智能导航](./baidu_map.ipynb)\n",
    "  - 零代码态调用：[AppBuilder控制台使用MCP](https://cloud.baidu.com/doc/AppBuilder/s/Nm9vmpb3g)\n",
    "- 被动调用：AppBuilder能力，融入MCP生态，可作为MCP Server提供能力\n",
    "  - 组件能力：[AppBuilder组件转MCP Server](./server.ipynb)\n",
    "  - 智能体能力：[AppBuilder Agent MCP Server](./app_mcp_server.ipynb)\n",
    "  - AI搜索能力: [AppBuilder AI搜索MCP Server](https://github.com/baidubce/app-builder/tree/master/python/mcp_server/ai_search)\n",
    "  - RAG能力：[AppBuilder知识库MCP Server](./knowledge_base_mcp_server.ipynb)\n",
    "\n",
    "\n",
    "## AppBuilder Agent MCP Server简介\n",
    "千帆AppBuilder提供了关于AppBuilder知识库的MCP Server，用户可通过MCP协议调用在AppBuilder中的知识库。当前包括以下能力：\n",
    "- 创建知识库\n",
    "- 获取知识库详情\n",
    "- 获取知识库列表\n",
    "- 知识库检索\n",
    "- 上传知识库文档\n",
    "- 获取文档列表\n",
    "\n",
    "对于入门用户，还提供了环境配置、 api key获取等操作步骤。已熟悉用户可以直接跳过环境配置、api_key获取部分。\n",
    "\n",
    "## 安装配置步骤\n",
    "\n",
    "### 配置基础环境\n",
    "\n",
    "#### 1、安装Python\n",
    "\n",
    "大部分的MCP Server，例如Unity和Blender，都是Python SDK\n",
    "安装Python最简单的方法是安装Miniconda\n",
    "**注意：请确保安装的python>=3.12**\n",
    "\n",
    "[Miniconda官网](https://www.anaconda.com/docs/getting-started/miniconda/install)\n",
    "\n",
    "#### 2、下载Appbuilder-SDK\n",
    "\n",
    "为了实现Appbuilder-SDK对AppBuilder Agent MCP Server的代码态调用，需要在conda环境下载appbuilder-sdk包\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96a39a88",
   "metadata": {
    "vscode": {
     "languageId": "shellscript"
    }
   },
   "outputs": [],
   "source": [
    "!python3 -m pip install httpx appbuilder-sdk mcp"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e7d417d",
   "metadata": {},
   "source": [
    "\n",
    "## 获取千帆AppBuilder API key\n",
    "\n",
    "### 1、进入百度智能云千帆AppBuilder主页\n",
    "\n",
    "进入百度智能云千帆AppBuilder主页，免费试用\n",
    "\n",
    "- [百度智能云千帆AppBuilder主页](https://qianfan.cloud.baidu.com/appbuilder)\n",
    "\n",
    "\n",
    "### 7、创建Appbuilder API key\n",
    "\n",
    "- [Appbuilder API key授权](https://cloud.baidu.com/doc/AppBuilder/s/lm68r8e6i)\n",
    "\n",
    "- [Appbuilder API 控制台管理中心](https://console.bce.baidu.com/iam/#/iam/apikey/list)\n",
    "\n",
    "在【API Key】界面中，创建一个新的Key，并添加知识库的读写权限，记下来。\n",
    "\n",
    "![](https://bj.bcebos.com/v1/appbuilder-sdk-components/%E5%88%9B%E5%BB%BAAPPBUILDER-TOKEN.png?authorization=bce-auth-v1%2FALTAKGa8m4qCUasgoljdEDAzLm%2F2025-04-17T14%3A49%3A27Z%2F-1%2Fhost%2F9266ac8c93a262d2905811877d680f53af26668a0ee09e1b3a61c0b721de253c)\n",
    "\n",
    "![api_key_knowledgebase](./image/api_key_knowledgebase.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3aa3c0a2",
   "metadata": {},
   "source": [
    "## 使用AppBuilder SDK调用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3e7b9a90",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "import json\n",
    "import io\n",
    "import os\n",
    "import appbuilder\n",
    "from appbuilder.mcp_server.client import MCPClient\n",
    "\n",
    "os.environ[\"APPBUILDER_TOKEN\"] = \"YOUR_APPBUILDER_TOKEN\"\n",
    "\n",
    "async def main():\n",
    "    mcp_client = MCPClient()\n",
    "    await mcp_client.connect_to_server(service_url=service_url)\n",
    "\n",
    "    # 创建知识库\n",
    "    result = await mcp_client.call_tool(\n",
    "        \"create_knowledge_base\",\n",
    "        {\"name\": \"mcp测试可删\", \"description\": \"mcp测试，可删\"},\n",
    "    )\n",
    "    knowledge_base_info = json.loads(result.content[0].text)\n",
    "    knowledge_base_id = knowledge_base_info.get(\"id\")\n",
    "    assert knowledge_base_id is not None\n",
    "    appbuilder.logger.debug(f\"create knowledge base success: {knowledge_base_id}\")\n",
    "\n",
    "    # 获取知识库详情\n",
    "    result = await mcp_client.call_tool(\n",
    "        \"describe_knowledge_base\",\n",
    "        {\"id\": knowledge_base_id},\n",
    "    )\n",
    "    knowledge_base_info = json.loads(result.content[0].text)\n",
    "    knowledge_base_id = knowledge_base_info.get(\"id\")\n",
    "    assert knowledge_base_id is not None\n",
    "    appbuilder.logger.debug(f\"describe knowledge base success: {knowledge_base_id}\")\n",
    "\n",
    "    # 获取知识库列表\n",
    "    result = await mcp_client.call_tool(\n",
    "        \"list_knowledge_bases\",\n",
    "        {\"max_keys\": 10},\n",
    "    )\n",
    "    assert len(result.content) == 10\n",
    "    appbuilder.logger.debug(f\"list knowledge bases success: {len(result.content)}\")\n",
    "\n",
    "    # 上传文档到知识库\n",
    "    file_content = \"这里是你的文件内容字符串\"\n",
    "    with io.BytesIO(file_content.encode(\"utf-8\")) as f:\n",
    "        result = await mcp_client.call_tool(\n",
    "            \"upload_document\",\n",
    "            {\"id\": knowledge_base_id, \"file_data\": f, \"file_name\": \"test.txt\"},\n",
    "        )\n",
    "    document_info = json.loads(result.content[0].text)\n",
    "\n",
    "    document_id = document_info.get(\"documentId\")\n",
    "    assert document_id is not None\n",
    "    appbuilder.logger.debug(f\"upload document success: {document_id}\")\n",
    "\n",
    "    # 获取文档列表\n",
    "    result = await mcp_client.call_tool(\n",
    "        \"list_documents\",\n",
    "        {\"id\": knowledge_base_id},\n",
    "    )\n",
    "    appbuilder.logger.debug(f\"list documents base success: {knowledge_base_id}\")\n",
    "\n",
    "    # 检索知识库\n",
    "    result = await mcp_client.call_tool(\n",
    "        \"query_knowledge_base\",\n",
    "        {\"query\": \"分子\", \"id_list\": [knowledge_base_id]},\n",
    "    )\n",
    "    assert result.content[0].text is not None\n",
    "    appbuilder.logger.debug(\"query knowledge base success\")\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    appbuilder.logger.setLoglevel(\"DEBUG\")\n",
    "    service_url = (\n",
    "        \"http://appbuilder.baidu.com/v2/ai_search/mcp/sse?api_key=\"\n",
    "        + os.environ.get(\"APPBUILDER_TOKEN\")\n",
    "    )\n",
    "\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(main())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df473bce",
   "metadata": {},
   "source": [
    "用户选择其中需要的功能进行执行，比如创建知识库，打印如下：\n",
    "\n",
    "```\n",
    "DEBUG:appbuilder:create knowledge base success: 909*****-***a-****-****-*********2c93\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b68c4d6",
   "metadata": {},
   "source": [
    "## 使用Cursor调用\n",
    "### Cursor配置\n",
    "api_key=上面步骤获取到的api key，格式为\"bce-v3/ALTAK...\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b292ee1",
   "metadata": {
    "vscode": {
     "languageId": "json"
    }
   },
   "outputs": [],
   "source": [
    "{\n",
    "    \"mcpServers\": {\n",
    "        \"AppBuilder RAG\": {\n",
    "            \"url\": \"http://appbuilder.baidu.com/v2/knowledgeBase/mcp/sse?api_key=bce-v3/ALTAK...\"\n",
    "        }\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "804d655d",
   "metadata": {},
   "source": [
    "配置后，在Cursor设置页面可看到`create_knowledge_base`、`describe_knowledge_base`、`list_knowledge_bases`、`query_knowledge_base`、`upload_document`、`list_documents` 6个Tool。\n",
    "![cursor config](./image/cursor_knowledgebase_config.png)\n",
    "\n",
    "### 调用\n",
    "![cursor knowledgebase](./image/cursor_knowledgebase_test.png)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
